package com.tbvtc.agriculturalcreditchainserver2025.service.impl;

import com.tbvtc.agriculturalcreditchainserver2025.exception.FoodException;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.AuthMapper;
import com.tbvtc.agriculturalcreditchainserver2025.service.IpfsService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.ResultCodeEnum;
import io.ipfs.api.IPFS;
import io.ipfs.api.MerkleNode;
import io.ipfs.api.NamedStreamable;
import io.ipfs.multihash.Multihash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class IpfsServiceImpl implements IpfsService {
    @Autowired
    private AuthMapper authMapper;
    // ipfs 的服务器地址和端口，与yaml文件中的配置对应
    @Value("${ipfs.config.multi-addr}")
    private String multiAddr;

    private IPFS ipfs;

    @PostConstruct  //  再加入ioc容器之前执行
    public void setMultiAddr() {
        ipfs = new IPFS(multiAddr);
    }

    @Override
    public String uploadToIpfs(String filePath) throws IOException {
        NamedStreamable.FileWrapper file = new NamedStreamable.FileWrapper(new File(filePath));
        MerkleNode addResult = ipfs.add(file).get(0);
        return addResult.hash.toString();
    }

    @Override
    public String uploadToIpfs(byte[] data) throws IOException {
        NamedStreamable.ByteArrayWrapper file = new NamedStreamable.ByteArrayWrapper(data); // 创建一个字节数组包装器
        MerkleNode addResult = ipfs.add(file).get(0); // 获取文件哈希
        String hash =addResult.hash.toString();
        return hash; // 返回文件哈希
    }

    @Override
    public byte[] downFromIpfs(String hash) {
        byte[] data = null;
        try {
            data = ipfs.cat(Multihash.fromBase58(hash));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    @Override
    public void downFromIpfs(String hash, String destFilePath) {

    }



    public List<Multihash> rmFromIpfs(String hash) {
        List<Multihash> rm;
        try {
            rm = ipfs.pin.rm(Multihash.fromBase58(hash)); // 删除文件
            ipfs.repo.gc();
        } catch (IOException e) {
            throw new FoodException(ResultCodeEnum. ADMIN_DELETE_FAIL);
        }
        return rm;
    }
}